// pages/index/index.js
const api = require('../../utils/api');

Page({
  data: {
    currentCity: '长沙',
    keyword: '',
    selectedType: 1, // 初始不选中任何选项
    venueTypes: [
      { id: 1, name: '棋牌', icon: '/images/icon/people.png' },
      { id: 2, name: '台球', icon: '/images/icon/ball.png' },
      { id: 3, name: 'KTV', icon: '/images/icon/ktv.png' }
    ],
    bannerList: [],
    nearbyVenues: [],
    hotVenues: [],
    loading: false,
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loadingMore: false,
    latitude: 0,
    longitude: 0,
    banners: [],
    venueTypes: [],
    // 悬浮按钮相关数据
    showFloatMenu: false, // 控制辅助功能图标的显示状态
  },
  
  onLoad: function(options) {
    wx.hideTabBar();
    this.getCurrentLocation();
    this.loadBanners();
    this.loadHotVenues();
    this.loadVenueTypes(); // 在这个函数中会加载场馆类型并加载门店数据
  },
  
  onShow: function() {
    // 每次页面显示时检查登录状态
    this.checkLoginStatus();
  },
  
  // 检查登录状态
  checkLoginStatus: function() {
    const app = getApp();
    if (app.globalData.isLoggedIn) {
      this.setData({
        isLoggedIn: true,
        userInfo: app.globalData.userInfo
      });
    }
  },
  
  // 点击城市选择
  onTapCitySelect: function() {
    wx.navigateTo({
      url: '/pages/venue/city',
      events: {
        // 监听城市选择页面返回的事件
        citySelected: (data) => {
          // 更新当前城市
          this.setData({
            currentCity: data.city
          });
          
          // 重新加载门店数据
          this.setData({
            pageNum: 1,
            loading: true,
            hasMore: true,
            loadingMore: false
          });
          this.loadNearbyVenues(this.data.selectedType);
        }
      }
    });
  },
  
  // 点击通知图标
  onTapNotification: function() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },
  
  // 搜索框输入事件处理
  onInputSearch: function(e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  
  // 点击搜索按钮
  onTapSearch: function() {
    const keyword = this.data.keyword;
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      loading: true,
      hasMore: false
    });
    
    // 通过API接口搜索门店
    api.store.searchStores({
      keyword: keyword,
      page: 1,
      limit: 20
    }).then(res => {
      if (res.data && res.data.list) {
        this.setData({
          nearbyVenues: res.data.list,
          loading: false
        });
        
        // 如果没有搜索结果，显示提示
        if (res.data.list.length === 0) {
          wx.showToast({
            title: '没有找到相关门店',
            icon: 'none'
          });
        }
      } else {
        this.setData({
          loading: false
        });
        wx.showToast({
          title: '搜索失败，请重试',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('搜索门店失败', err);
      this.setData({
        loading: false
      });
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    });
  },
  
  // 点击轮播图
  onTapBanner: function(e) {
    const url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    });
  },
  
  // 点击场馆类型
  // 根据type_id获取场地类型名称
  getVenueTypeNames: function(typeIds, venueTypes) {
    if (!typeIds || !venueTypes) {
      return '';
    }
    const typeNames = typeIds.map(id => {
      const type = venueTypes.find(t => t.id === id);
      return type ? type.name : '';
    });
    return typeNames.filter(name => name).join('/');
  },

  formatDetailedBusinessHours: function(businessHours) {
    if (!businessHours) {
        return ['24小时营业'];
    }
    try {
        const hours = typeof businessHours === 'string' ? JSON.parse(businessHours) : businessHours;
        const result = [];

        const formatLine = (day, schedule) => {
            if (schedule.isOpen) {
                if (schedule.openTime === '00:00' && schedule.closeTime === '23:59') {
                    return `${day}: 24小时营业`;
                }
                return `${day}: ${schedule.openTime} - ${schedule.closeTime}`;
            } else {
                return `${day}: 休息`;
            }
        };

        if (hours.daily && hours.daily.length === 7) {
            const workday = hours.daily.slice(0, 5);
            const weekend = hours.daily.slice(5, 7);
            const workdaySame = workday.every(d => d.isOpen === workday[0].isOpen && d.openTime === workday[0].openTime && d.closeTime === workday[0].closeTime);
            const weekendSame = weekend.every(d => d.isOpen === weekend[0].isOpen && d.openTime === weekend[0].openTime && d.closeTime === weekend[0].closeTime);

            if (workdaySame && weekendSame) {
                result.push(formatLine('周一至周五', workday[0]));
                result.push(formatLine('周六至周日', weekend[0]));
                return result;
            }

            // Otherwise, list day by day
            hours.daily.forEach(dayInfo => {
                result.push(formatLine(dayInfo.dayName, dayInfo));
            });
            return result;

        } else {
             // Fallback for older format
            if (hours.workday) {
                result.push(formatLine('工作日', hours.workday));
            }
            if (hours.weekend) {
                result.push(formatLine('周末', hours.weekend));
            }
        }

        return result.length > 0 ? result : ['暂无营业时间信息'];

    } catch (e) {
        console.error('Error parsing detailed businessHours', e);
        return ['24小时营业'];
    }
  },

  formatBusinessHours: function(businessHours) {
    if (!businessHours) {
      return '24小时营业';
    }
    try {
      const hours = typeof businessHours === 'string' ? JSON.parse(businessHours) : businessHours;
      const today = new Date().getDay();
      const dayIndex = today === 0 ? 6 : today - 1;

      if (hours.daily && hours.daily[dayIndex]) {
        const dayInfo = hours.daily[dayIndex];
        if (dayInfo.isOpen) {
          if (dayInfo.openTime === '00:00' && dayInfo.closeTime === '23:59') {
            return '24小时营业';
          }
          return `营业时间 ${dayInfo.openTime} - ${dayInfo.closeTime}`;
        } else {
          return '休息中';
        }
      }
      
      if (today >= 1 && today <= 5 && hours.workday && hours.workday.isOpen) {
         if (hours.workday.openTime === '00:00' && hours.workday.closeTime === '23:59') {
            return '24小时营业';
          }
        return `营业时间 ${hours.workday.openTime} - ${hours.workday.closeTime}`;
      }
      if ((today === 0 || today === 6) && hours.weekend && hours.weekend.isOpen) {
        if (hours.weekend.openTime === '00:00' && hours.weekend.closeTime === '23:59') {
            return '24小时营业';
          }
        return `营业时间 ${hours.weekend.openTime} - ${hours.weekend.closeTime}`;
      }
      return '休息中';
    } catch (e) {
      console.error('Error parsing businessHours', e);
      return '24小时营业';
    }
  },

  onTapVenueType: function(e) {
    const id = e.currentTarget.dataset.id;
    const typeId = parseInt(id);
    this.setData({
      selectedType: typeId,
      loading: true,
      pageNum: 1, // 重置页码
      nearbyVenues: [] // 清空现有列表
    });

    // 获取对应类型的场馆数据
    this.loadNearbyVenues(typeId);
  },

  // 点击前往预定
  onTapBookNow: function(e) {
    const venueId = e.currentTarget.dataset.venueId;
    const venueName = e.currentTarget.dataset.venueName;
    wx.setStorageSync('currentStoreName', venueName);
    wx.setStorageSync('currentStoreId', venueId);
    wx.reLaunch({
      url: '/pages/venue/room?venueId=' + venueId
    });
  },
  
  // 加载轮播图数据
  loadBanners: function() {
    this.setData({ loading: true });
    api.banner.getBannerList()
      .then(res => {
        this.setData({
          bannerList: res.data.list || [{ id: 1, imageUrl: '/images/banner/default.png', linkUrl: '/pages/venue/detail?id=1' }],
          loading: false
        });
      })
      .catch(err => {
        console.error('获取轮播图失败:', err);
        // 使用默认数据作为备用
        this.setData({
          bannerList: [
            { id: 1, imageUrl: '/images/banner/default.png', linkUrl: '/pages/venue/detail?id=1' }
          ],
          loading: false
        });
      });
  },
  
  // 获取当前位置
  getCurrentLocation: function () {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        // 获取附近门店
        this.loadNearbyVenues();
      },
      fail: (err) => {
        console.error('获取位置失败', err);
        // 即使获取位置失败，也加载门店列表
        this.loadNearbyVenues();
      }
    });
  },
  
  // 加载附近门店
  loadNearbyVenues: function (typeId = 0) {
    const { pageNum, pageSize, latitude, longitude, loadingMore, currentCity } = this.data;
    
    // 设置加载状态
    this.setData({
      loading: !loadingMore, // 如果是加载更多，不显示主loading
      loadingMore: loadingMore
    });
    
    // 构建请求参数
    const params = {
      page: pageNum,
      limit: pageSize,
      latitude,
      longitude,
      city: currentCity
    };
    
    // 如果有类型筛选
    if (typeId > 0) {
      params.type_id = typeId;
    }
    
    // 请求接口
    api.store.getNearbyStores(params)
      .then(res => {
        if (res.data && res.data.list) {
          const newList = res.data.list || [];
          const processedVenues = newList.map(venue => {
            venue.type_name = this.getVenueTypeNames(venue.type_id, this.data.venueTypes);
            venue.business_hours_text = this.formatBusinessHours(venue.business_hours);
            venue.detailed_business_hours = this.formatDetailedBusinessHours(venue.business_hours);
            return venue;
          });

          // 更新数据
          this.setData({
            nearbyVenues: loadingMore ? [...this.data.nearbyVenues, ...processedVenues] : processedVenues,
            loading: false,
            loadingMore: false,
            hasMore: newList.length >= pageSize // 如果返回的数量等于pageSize，说明可能还有更多数据
          });
        } else {
          wx.showToast({
            title: res.message || '加载门店失败',
            icon: 'none'
          });
          this.setData({
            loading: false,
            loadingMore: false
          });
        }
      })
      .catch(err => {
        console.error('加载附近门店失败', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
        this.setData({
          loading: false,
          loadingMore: false
        });
      });
  },
  
  // 加载热门门店
  loadHotVenues: function () {
    api.store.getHotStores({ limit: 5 })
      .then(res => {
        if (res.data && res.data.list) {
          this.setData({
            hotVenues: res.data.list || []
          });
        }
      })
      .catch(err => {
        console.error('加载热门门店失败', err);
      });
  },
  
  // 加载场地类型列表
  loadVenueTypes: function() {
    api.venue.getVenueTypes()
      .then(res => {
        if (res.success && res.data) {
          // 获取类型列表
          const types = res.data.list || [];
          
          // 添加"全部"类型选项
          const allTypes = [
            { id: 0, name: '全部', icon: '/images/icon/all.png' },
            ...types
          ];
          
          // 设置默认选中全部
          this.setData({ 
            venueTypes: allTypes,
            selectedType: 0 // 默认选择"全部"
          });
          
          // 加载门店数据，不带类型筛选
          this.loadNearbyVenues(0);
        }
      })
      .catch(err => {
        console.error('获取场馆类型失败', err);
        // 设置默认类型数据
        this.setData({
          venueTypes: [],
          selectedType: 0 // 默认选择"全部"
        });
        
        // 加载门店数据，不带类型筛选
        this.loadNearbyVenues(0);
      });
  },
  
  // 页面上拉触底事件处理函数
  onReachBottom: function() {
    if (this.data.hasMore && !this.data.loadingMore) {
      // 设置加载更多状态
      this.setData({
        pageNum: this.data.pageNum + 1,
        loadingMore: true
      });
      
      // 加载更多数据
      this.loadNearbyVenues();
    }
  },
  
  // 拨打客服电话
  onTapCall: function() {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567' // 客服电话号码
    });
  },
  
  // 点击地图按钮，跳转到地图详情页
  onTapMap: function(e) {
    const venueId = e.currentTarget.dataset.venueId;
    wx.navigateTo({
      url: '/pages/venue/map?id=' + venueId
    });
  },
  
  // 悬浮按钮相关事件处理函数
  // 点击主悬浮按钮，切换辅助功能图标的显示状态
  toggleFloatMenu: function() {
    this.setData({
      showFloatMenu: !this.data.showFloatMenu
    });
  },
  
  // 开包厢功能
  onTapOpenDoor: function() {
    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({
        url: '/pages/user/login'
      });
      return;
    }
    
    // 获取当前用户的预约信息
    wx.showLoading({
      title: '正在获取预约信息',
      mask: true
    });
    
    // 获取用户当前的预约订单
    api.order.getMyBookings({status: 1}) // 状态1表示已确认的预约
      .then(res => {
        wx.hideLoading();
        if (res.data && res.data.list && res.data.list.length > 0) {
          // 有正在进行的预约，弹出选择框
          const bookings = res.data.list;
          if (bookings.length === 1) {
            // 只有一个预约，直接开门
            this.openDoorForBooking(bookings[0]);
          } else {
            // 多个预约，让用户选择
            wx.showActionSheet({
              itemList: bookings.map(booking => `${booking.store_id} - ${booking.venue_id}`),
              success: (res) => {
                if (res.tapIndex >= 0) {
                  this.openDoorForBooking(bookings[res.tapIndex]);
                }
              }
            });
          }
        } else {
          // 没有正在进行的预约
          wx.showModal({
            title: '提示',
            content: '您当前没有正在进行的预约，无法开门',
            showCancel: false
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: '获取预约信息失败',
          icon: 'none'
        });
        console.error('获取预约信息失败', err);
      });
    
    // 隐藏菜单
    this.setData({
      showFloatMenu: false
    });
  },
  
  // 为指定预约开门
  openDoorForBooking: function(booking) {
    wx.showLoading({
      title: '正在开门',
      mask: true
    });
    
    api.device.openDoor({
      store_id: booking.store_id,
      room_id: booking.room_id
    })
      .then(res => {
        wx.hideLoading();
        if (res.success) {
          wx.showToast({
            title: '开门成功',
            icon: 'success'
          });
        } else {
          wx.showModal({
            title: '开门失败',
            content: res.message || '请稍后再试',
            showCancel: false
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        wx.showModal({
          title: '开门失败',
          content: '网络错误，请稍后再试',
          showCancel: false
        });
        console.error('开门失败', err);
      });
  },
  
  // 开大门功能
  onTapOpenGate: function() {
    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({
        url: '/pages/user/login'
      });
      return;
    }
    
    // 获取当前用户的预约信息
    wx.showLoading({
      title: '正在获取门店信息',
      mask: true
    });
    
    // 获取用户当前的预约订单，用于确定用户有权限开哪些门店的大门
    api.order.getMyBookings({status: 1}) // 状态1表示已确认的预约
      .then(res => {
        wx.hideLoading();
        if (res.data && res.data.list && res.data.list.length > 0) {
          // 有正在进行的预约，弹出选择框
          const bookings = res.data.list;
          // 提取不重复的门店
          const stores = [];
          const storeIds = new Set();
          
          bookings.forEach(booking => {
            if (!storeIds.has(booking.store_id)) {
              storeIds.add(booking.store_id);
              stores.push({
                id: booking.store_id,
                name: booking.store_name
              });
            }
          });
          
          if (stores.length === 1) {
            // 只有一个门店，直接开门
            this.openGateForStore(stores[0]);
          } else if (stores.length > 1) {
            // 多个门店，让用户选择
            wx.showActionSheet({
              itemList: stores.map(store => store.name),
              success: (res) => {
                if (res.tapIndex >= 0) {
                  this.openGateForStore(stores[res.tapIndex]);
                }
              }
            });
          }
        } else {
          // 没有正在进行的预约
          wx.showModal({
            title: '提示',
            content: '您当前没有正在进行的预约，无法开门',
            showCancel: false
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: '获取门店信息失败',
          icon: 'none'
        });
        console.error('获取门店信息失败', err);
      });
    
    // 隐藏菜单
    this.setData({
      showFloatMenu: false
    });
  },
  
  // 为指定门店开大门
  openGateForStore: function(store) {
    wx.showLoading({
      title: '正在开门',
      mask: true
    });
    
    // 调用开大门API，这里假设API路径为/mini/auth/device/open_gate
    // 如果实际API不同，需要修改
    wx.request({
      url: getApp().globalData.apiBaseUrl + '/mini/auth/device/open_gate',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      data: {
        store_id: store.id
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data && res.data.success) {
          wx.showToast({
            title: '开门成功',
            icon: 'success'
          });
        } else {
          wx.showModal({
            title: '开门失败',
            content: (res.data && res.data.message) || '请稍后再试',
            showCancel: false
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showModal({
          title: '开门失败',
          content: '网络错误，请稍后再试',
          showCancel: false
        });
        console.error('开大门失败', err);
      }
    });
  },
  
  // 续费功能
  onTapRenew: function() {
    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({
        url: '/pages/user/login'
      });
      return;
    }
    
    // 获取可续费的预约
    wx.showLoading({
      title: '正在获取可续费订单',
      mask: true
    });
    
    // 获取用户可续费的订单
    api.order.getMyRenewableBookings()
      .then(res => {
        wx.hideLoading();
        if (res.data && res.data.list && res.data.list.length > 0) {
          // 有可续费的预约
          const bookings = res.data.list;
          if (bookings.length === 1) {
            // 只有一个可续费的预约，直接跳转到续费页面
            wx.navigateTo({
              url: `/pages/booking/renew?id=${bookings[0].id}`
            });
          } else {
            // 多个可续费的预约，让用户选择
            wx.showActionSheet({
              itemList: bookings.map(booking => `${booking.store_name} - ${booking.store_id} - ${booking.venue_id}`),
              success: (res) => {
                if (res.tapIndex >= 0) {
                  wx.navigateTo({
                    url: `/pages/booking/renew?id=${bookings[res.tapIndex].id}`
                  });
                }
              }
            });
          }
        } else {
          // 没有可续费的预约
          wx.showModal({
            title: '提示',
            content: '您当前没有可续费的预约',
            showCancel: false
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: '获取可续费订单失败',
          icon: 'none'
        });
        console.error('获取可续费订单失败', err);
      });
    
    // 隐藏菜单
    this.setData({
      showFloatMenu: false
    });
  },
  
  // 分享功能
  onTapShare: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    // 隐藏菜单
    this.setData({
      showFloatMenu: false
    });
  }
});